import React from "react";
import { useImmer } from "use-immer";

interface FormObj {
  answer: string;
  error: Error | null;
  status: "typing" | "success" | "submitting";
}
const Form: React.FC = () => {
  const [formObj, updateFormObj] = useImmer<FormObj>({
    answer: "",
    error: null,
    status: "typing"
  });

  function submitForm(answer: string) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        const shouldError = answer.toLowerCase() !== "shanghai";
        if (shouldError) {
          reject(new Error("猜的不错，但答案不对，再试试看吧！"));
        } else {
          resolve("猜对了");
        }
      }, 1500);
    });
  }

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    updateFormObj(draft => {
      draft.status = "submitting";
    });

    try {
      await submitForm(formObj.answer);
      updateFormObj(draft => {
        draft.status = "success";
      });
    } catch (error) {
      updateFormObj(draft => {
        draft.status = "typing";
        draft.error = error as Error;
      });
    }
  }

  function handleTextChange(e: React.ChangeEvent<HTMLTextAreaElement>) {
    updateFormObj(draft => {
      draft.answer = e.target.value;
    });
  }

  if (formObj.status === "success") {
    return <h2>恭喜了，答对了。</h2>;
  }

  return (
    <>
      <h2>城市测验</h2>
      <p>哪个城市有把空气变成饮用水的广告牌？</p>
      <form onSubmit={handleSubmit}>
        <textarea value={formObj.answer} onChange={handleTextChange} disabled={formObj.status === "submitting"} />
        <br />
        <button disabled={formObj.status === "submitting" || formObj.answer.length === 0}>提交</button>
        {formObj.error !== null && <p style={{ color: "red" }}>{formObj.error.message}</p>}
      </form>
    </>
  );
};
export default Form;
